package cn.smbms.controller;

import cn.smbms.pojo.Role;
import cn.smbms.pojo.User;
import cn.smbms.service.role.RoleService;
import cn.smbms.service.role.RoleServiceImpl;
import cn.smbms.service.user.UserService;
import cn.smbms.tools.Constants;
import cn.smbms.tools.PageSupport;
import com.alibaba.fastjson.JSONArray;
import com.mysql.jdbc.StringUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public String login(String userCode, String userPassword, HttpSession session, HttpServletRequest request){
        System.out.println("login ============ " );


        User user = userService.login(userCode,userPassword);
        if(null != user){//登录成功
            session.setAttribute(Constants.USER_SESSION, user);
            //页面跳转（frame.jsp）
            return "redirect:/user/sys/main.html";
        }else{
            request.setAttribute("error","用户名或密码错误");
            return "login";
        }

    }
    @RequestMapping("/sys/main.html")
    public String main(){
        return "frame";
    }

   /* @ExceptionHandler(value={RuntimeException.class})
    public String handlerException(RuntimeException e,HttpServletRequest request){
        request.setAttribute("e",e);
        return "error";
    }*/
   @RequestMapping("/userlist")
   public String userlist(String queryname,Integer queryUserRole,Integer pageIndex,
                            HttpServletRequest request){

       List<User> userList = null;
       //设置页面容量
       int pageSize = Constants.pageSize;
       //当前页码
       int currentPageNo = 1;
       /**
        * http://localhost:8090/SMBMS/userlist.do
        * ----queryUserName --NULL
        * http://localhost:8090/SMBMS/userlist.do?queryname=
        * --queryUserName ---""
        */

       if(queryname == null){
           queryname = "";
       }
      if(queryUserRole==null){
          queryUserRole=0;
      }

       if(pageIndex != null){
           try{
               currentPageNo = pageIndex;
           }catch(NumberFormatException e){
               return "error";
           }
       }
       //总数量（表）
       int totalCount	= userService.getUserCount(queryname,queryUserRole);
       //总页数
       PageSupport pages=new PageSupport();
       pages.setCurrentPageNo(currentPageNo);
       pages.setPageSize(pageSize);
       pages.setTotalCount(totalCount);

       int totalPageCount = pages.getTotalPageCount();

       //控制首页和尾页
       if(currentPageNo < 1){
           currentPageNo = 1;
       }else if(currentPageNo > totalPageCount){
           currentPageNo = totalPageCount;
       }


       userList = userService.getUserList(queryname,queryUserRole,currentPageNo, pageSize);
       request.setAttribute("userList", userList);
       List<Role> roleList = null;
       RoleService roleService = new RoleServiceImpl();
       roleList = roleService.getRoleList();
       request.setAttribute("roleList", roleList);
       request.setAttribute("queryUserName", queryname);
       request.setAttribute("queryUserRole", queryUserRole);
       request.setAttribute("totalPageCount", totalPageCount);
       request.setAttribute("totalCount", totalCount);
       request.setAttribute("currentPageNo", currentPageNo);
       return "userlist";
   }

    @RequestMapping("/useradd.html")
    public String useradd(){
        return "useradd";
    }

    @RequestMapping("/useradd")
    public String useraddSave(User user, HttpSession session, HttpServletRequest request,
                              @RequestParam(value="attachs",required = false) MultipartFile[] attaches){
        System.out.println("add()================");
        String idPicPath="";
        String workPicPath="";
        String erroInfo="";
        for (int i = 0; i <attaches.length ; i++) {
            MultipartFile attach=attaches[i];
            if(!attach.isEmpty()){
                if(i==0){
                    erroInfo="uploadFileError";
                }else if(i==1){
                    erroInfo="uploadFileErrorwork";
                }
                //定义上传的路径
                String picPath= session.getServletContext().getRealPath("statics"+ File.separator+"upload");
                //获取源文件的名称
                String oldName=attach.getOriginalFilename();
                //获取后缀
                String suffix= FilenameUtils.getExtension(oldName);
                //获取文件大小
                long fileSize=attach.getSize();
                if(fileSize>5000000){
                    request.setAttribute(erroInfo,"文件大小不能超过500KB");
                    return "useradd";
                }else if(suffix.equalsIgnoreCase("jpg")
                        ||suffix.equalsIgnoreCase("png")
                        ||suffix.equalsIgnoreCase("jpeg")
                        ||suffix.equalsIgnoreCase("pneg")){
                    //重新定义文件的名字

                    String newfileName=System.currentTimeMillis()+ RandomUtils.nextInt(1000000)+"."+suffix;
                    //创建目标文件对象
                    File targetFile=new File(picPath,newfileName);
                    if(!targetFile.exists()){
                        targetFile.mkdirs();
                    }
                    try {
                        //上传文件
                        attach.transferTo(targetFile);
                    } catch (IOException e) {

                        request.setAttribute(erroInfo,"上传文件失败");
                        return "useradd";
                    }
                    if(i==0){
                        idPicPath=picPath+File.separator+newfileName;
                    }else if(i==1){
                        workPicPath=picPath+File.separator+newfileName;
                    }
                }else{
                    request.setAttribute(erroInfo,"上传文件格式不正确");
                    return "useradd";
                }

        }


        }
        user.setCreationDate(new Date());
        user.setCreatedBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
        user.setIdPicPath(idPicPath);
        user.setWorkPicPath(workPicPath);
        if(userService.add(user)){
            return "redirect:/user/userlist";
        }else{
            return "useradd";
        }
    }
    /*@RequestMapping(value="/useradd.html",method = RequestMethod.GET)
    public String useraddPage(@ModelAttribute("user")User user){return "useraddfm";}

    @RequestMapping(value="/useradd.html",method = RequestMethod.POST)
    public String useradd(@Valid User user, BindingResult result,HttpSession session){
        user.setCreationDate(new Date());
        user.setCreatedBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
        if(result.hasErrors()){
            System.out.println("验证出错");
            return "useraddfm";
        }
        if(userService.add(user)){
            return "redirect:/user/userlist";
        }else{
            return "useraddfm";
        }
    }*/



    @RequestMapping("/modifyuser")
    public String modifyuser(String uid, Model model){
        User user=userService.getUserById(uid);
        model.addAttribute("user",user);
        return "usermodify";
    }

    @RequestMapping("/usermodifySave")
    public String usermodifySave(User user, HttpSession session){
        user.setModifyBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
        user.setModifyDate(new Date());
       if( userService.modify(user)){
           return "redirect:/user/userlist";
       }
       return "usermodify";
    }

    @RequestMapping(value="/userview/{id}",method = RequestMethod.GET)
    public String userview(@PathVariable String id, Model model){
        User user=userService.getUserById(id);
        model.addAttribute("user",user);
        return "userview";
    }
    @RequestMapping("/checkUserCode")
    @ResponseBody
    public Object checkUserCode(String userCode){
        HashMap<String,String> map=new HashMap<String,String>();
        if(StringUtils.isNullOrEmpty(userCode)){
            map.put("userCode","exist");
        }else{
            User user=userService.selectUserCodeExist(userCode);
            if(null!=user){
                map.put("userCode","exist");
            }else{
                map.put("userCode","noexits");
            }
        }
        String str= JSONArray.toJSONString(map);
        System.out.println(str);
        return JSONArray.toJSONString(map);
    }
    @RequestMapping(value="/view",method= RequestMethod.GET)
    @ResponseBody
    public User view(@RequestParam String id){
        User user = new User();
        try {
            user = userService.getUserById(id);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return user;
    }

}
